package com.sixmac.controller;

import com.sixmac.annotation.AuthUser;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.module.*;
import com.sixmac.platform.service.IndexService;
import com.sixmac.util.Push;
import com.sixmac.util.WeChatConfig;
import com.sixmac.utils.LockManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by admin on 2018/9/4.
 */
@Controller
@ResponseBody
@RequestMapping("index")
public class IndexController extends BaseController {
    @Autowired
    IndexService indexService;
    @Autowired
    WeChatConfig weChatConfig;

    /**
     * @api {post} /index/applyKey 0.1.1 申请密钥
     * @apiName index.applyKey
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} lockNo
     * @apiSuccess {String} user.code 1成功0失败
     */
    @AuthUser
    @RequestMapping("/applyKey")
    public AjaxResult applyKey(Tenant tenant,String lockNo) {
        return indexService.applyKey(tenant,lockNo);
    }

    /**
     * @api {post} /index/doApplyKey 0.1.2 上传申请密钥的资料
     * @apiName index.doApplyKey
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} roomNo 房号
     * @apiParam {String} form_id 小程序消息推送form_id
     * @apiParam {String} contract 合同图片
     */
    @AuthUser
    @RequestMapping("/doApplyKey")
    public AjaxResult doApplyKey(Tenant tenant, String roomNo,String form_id, String contract) {
        return indexService.doApplyKey(tenant, roomNo,form_id, contract);
    }

    /**
     * @api {post} /index/record NB锁录入指纹
     * @apiName index.record
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} form_id 小程序消息推送form_id
     */
    @AuthUser
    @RequestMapping("/record")
    public AjaxResult record(Tenant tenant, String form_id) {
        return indexService.record(tenant,form_id);
    }

    @AuthUser
    @RequestMapping("/getDelete")
    public AjaxResult getDelete(Tenant tenant, String roomId) {
        String ids = Db.queryStr("SELECT  GROUP_CONCAT(tenantId) tenantIds FROM t_tenant_room where roomId = " + roomId + " AND fingerprint is not null and ifnull(deleteStatus,0)!=1 AND status = 2", null);
        return json(ids);
    }

    @AuthUser
    @RequestMapping("/deleteSucess")
    public AjaxResult deleteSucess(Tenant tenant, String userIds,String roomId) {
        Db.update("UPDATE t_tenant_room SET deleteStatus = 1 WHERE roomId = "+roomId+" and tenantId in ("+userIds+") and `status` = 2 ",null);
        return success("删除成功");
    }

    /**
     * @api {post} /index/recordBl 录入蓝牙指纹
     * @apiName index.recordBl
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} form_id 小程序消息推送form_id
     */
    @AuthUser
    @RequestMapping("/recordBl")
    public AjaxResult recordBl(Tenant tenant,Integer roomId,Integer fingerprint) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and roomId= "+roomId+" and tenantId="+tenant.getId(),null);
        tenantRoom.setDeleteStatus(0);
        Pay pay = Blade.create(Pay.class).findFirstBy(" trId= "+tenantRoom.getId()+" and isDo = 0",null);
        DayMoney dayMoney = Blade.create(DayMoney.class).findById(pay.getDayId());
        if (tenantRoom.getFingerprint() == null){
            tenantRoom.setFingerprint(fingerprint);
            tenantRoom.setPayId(pay.getId());
            tenantRoom.setLockStartTime(new Date());
            tenantRoom.setLockEndTime(DateKit.getAfterDayDate(new Date(),dayMoney.getDay()));
        }else{
            if (fingerprint!=null){
                tenantRoom.setFingerprint(fingerprint);
            }
            tenantRoom.setPayId(pay.getId());
            tenantRoom.setLockStartTime(tenantRoom.getLockStartTime());
            tenantRoom.setLockEndTime(DateKit.getAfterDayDate(tenantRoom.getLockEndTime(),dayMoney.getDay()));
        }
        pay.setPayTime(new Date());
        pay.setEndTime(DateKit.getAfterDayDate(new Date(),dayMoney.getDay()));
        pay.setIsDo(1);
        Blade.create(TenantRoom.class).update(tenantRoom);
        Blade.create(Pay.class).update(pay);
        return success("录入指纹成功");
    }


    /**
     * @api {post} /index/recordBl 录入蓝牙指纹
     * @apiName index.recordBl
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} form_id 小程序消息推送form_id
     */
    @AuthUser
    @RequestMapping("/updateBl")
    public AjaxResult updateBl(Tenant tenant,Integer roomId,Integer fingerprint) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and roomId= "+roomId+" and tenantId="+tenant.getId(),null);
        tenantRoom.setDeleteStatus(0);
        if (fingerprint!=null){
            tenantRoom.setFingerprint(fingerprint);
        }
        Blade.create(TenantRoom.class).update(tenantRoom);
        return success("修改指纹成功");
    }

    /**
     * @api {post} /index/apply 申请成为管理员
     * @apiName index.apply
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} form_id 小程序消息推送form_id
     */
    @AuthUser
    @RequestMapping("/apply")
    public AjaxResult apply(Tenant tenant,Integer roomId) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and roomId= "+roomId+" and tenantId="+tenant.getId(),null);
        tenantRoom.setIsAdmin(1);
        Blade.create(TenantRoom.class).update(tenantRoom);
        return success("管理员申请成功");
    }

    /**
     * @api {post} /index/openLock 0.2.1 进入开锁页面
     * @apiName index.openLock
     * @apiGroup index
     * @apiParam {String} token token
     */
    @AuthUser
    @RequestMapping("/openLock")
    public AjaxResult openLock(Tenant tenant,String form_id) {
        TenantRoom roomInfo = Blade.create(TenantRoom.class).findFirstBy("status = 1 and tenantId =" + tenant.getId(), null);
        if (roomInfo == null)
            return error("找不到房间");

        AccessFrom accessFrom = new AccessFrom();
        accessFrom.setCreatTime(new Date());
        accessFrom.setIsUse(0);
        accessFrom.setFormId(form_id);
        accessFrom.setType(1);
        accessFrom.setUserId(tenant.getId());
        Blade.create(AccessFrom.class).save(accessFrom);
        Room room = Blade.create(Room.class).findById(roomInfo.getRoomId());
        return json(getData("room", room));
    }

    @AuthUser
    @RequestMapping("/openHistory")
    public AjaxResult openHistory(Tenant tenant,Integer roomId) {
        TenantRoom roomInfo = Blade.create(TenantRoom.class).findFirstBy("status = 1 and tenantId =" + tenant.getId(), null);
        if (roomInfo == null)
            return error("找不到房间");

        OpenHistory openHistory = new OpenHistory();
        openHistory.setCreateDate(new Date());
        openHistory.setRoomId(roomId);
        openHistory.setType(0);
        openHistory.setTenantId(tenant.getId());
        Blade.create(OpenHistory.class).save(openHistory);
        return success("操作成功");
    }

    /**
     * @api {post} /index/doOpenLock 0.2.2 开锁
     * @apiName index.doOpenLock
     * @apiGroup index
     * @apiParam {String} token token
     * @apiParam {String} form_id 提交的form
     */
    @AuthUser
    @RequestMapping("/doOpenLock")
    public AjaxResult doOpenLock(Tenant tenant,String form_id) {

        Contract contract = Blade.create(Contract.class).findFirstBy(" tentantId="+tenant.getId()+" and status = 0",null);
        if (contract == null){
            return error("房间不存在");
        }

        if (new Date().getTime()<contract.getStartTime().getTime()){
            return error("不在租房时间范围内！");
        }

        if (new Date().getTime()>contract.getEndTime().getTime()){
            return error("不在租房时间范围内！");
        }

        AccessFrom accessFrom = new AccessFrom();
        accessFrom.setCreatTime(new Date());
        accessFrom.setIsUse(0);
        accessFrom.setFormId(form_id);
        accessFrom.setType(1);
        accessFrom.setUserId(tenant.getId());
        Blade.create(AccessFrom.class).save(accessFrom);

        Room room = Blade.create(Room.class).findById(contract.getRoomId());

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" tenantId="+tenant.getId()+" and roomId="+contract.getRoomId()+" and status = 1",null);

        LockUser lockUser = new LockUser();
        lockUser.setDeviceCode(room.getLockNo());
        lockUser.setUnlockWay("1");
        lockUser.setLockUserInfo("198721");
        lockUser.setMsgId("198722");
        lockUser.setLockUserType("12");
        lockUser.setStartDay(contract.getStartTime().getTime()/1000+"");
        lockUser.setEndDay(contract.getEndTime().getTime()/1000+"");
        lockUser.setUserFlag("100"+tenantRoom.getTenantId());
        LockManage lockManage = new LockManage();
        Boolean result = lockManage.openLock(lockUser);

        if(!result){
            return error("请点亮门锁。");
        }

        Push push = new Push();
        push.openClock(tenant,null,contract.getRoomId(),weChatConfig);

        return success("开锁成功。");
    }

    /**
     * @api {post} /index/cancelRoom 0.3 退租
     * @apiName index.cancelRoom
     * @apiGroup index
     * @apiParam {String} token token
     */
    @AuthUser
    @RequestMapping("/cancelRoom")
    public AjaxResult cancelRoom(Tenant tenant) {
        return indexService.cancelRoom(tenant);
    }

    @AuthUser
    @RequestMapping("/banner")
    public AjaxResult recordRoom(Tenant tenant) {
        List<Banner> banners = Blade.create(Banner.class).findBy(" type =2 ",null);
        return json(banners);
    }
}
